import {
  SETToken,
  SETUSERINFO,
  LOGOUT,
  SETUserInfoValues
} from '@/store/mutations-types'
import {
  signUpRequest,
  signInRequest,
  getUserInfo,
  editUserInfo
} from '@/api/user'
import {
  ActionsSignIn,
  ActionsSignUp,
  ActionsGetUserInfo,
  ActionsLogOut,
  ActionsEditUserInfo
} from '@/store/actions-type'
import { ACCESSTOKEN, USERINFO } from '@/store/state-types'
import { setToken, removeToken, getToken } from '@/utils/stroage/token'
import {
  UserInfoStroageKey,
  setUserInfoCache,
  getUserInfoCache,
  removeUserInfoCache
} from '@/utils/stroage/userinfo'
const user = {
  state: {
    [ACCESSTOKEN]: getToken(ACCESSTOKEN) || '',
    [USERINFO]: getUserInfoCache(UserInfoStroageKey) || {
      userInfo: {}
    }
  },
  getters: {},
  mutations: {
    [SETToken](state, token) {
      state[ACCESSTOKEN] = token
      setToken(ACCESSTOKEN, token)
    },
    [SETUSERINFO](state, userinfo) {
      state[USERINFO] = userinfo
      setUserInfoCache(UserInfoStroageKey, userinfo)
    },
    [LOGOUT](state) {
      removeToken(ACCESSTOKEN)
      state[ACCESSTOKEN] = ''
      removeUserInfoCache(UserInfoStroageKey)
      state[USERINFO] = { userInfo: {} }
    },
    [SETUserInfoValues](state, { key, value }) {
      state[USERINFO].userInfo[key] = value
      setUserInfoCache(UserInfoStroageKey, state[USERINFO])
    }
  },
  actions: {
    async [ActionsSignUp]({ commit }, signUpOption) {
      try {
        const { errmsg, errno } = await signUpRequest(signUpOption)
        console.log(errmsg, errno)
        if (errno !== 0) {
          return Promise.reject(errmsg)
        }
      } catch {
        const errmsg = '注册出现错误'
        return Promise.reject(errmsg)
      }
    },
    async [ActionsSignIn]({ commit }, signInOption) {
      try {
        const { errno, errmsg, data } = await signInRequest(signInOption)
        if (errno !== 0) {
          return Promise.reject(errmsg)
        }
        commit(SETToken, data.token)
      } catch {
        const errmsg = '登录出现错误'
        return Promise.reject(errmsg)
      }
    },
    async [ActionsGetUserInfo]({ commit }) {
      try {
        const { errno, data } = await getUserInfo()
        if (errno === 0) {
          commit(SETUSERINFO, data)
        } else {
          return Promise.reject(new Error(''))
        }
      } catch {
        return Promise.reject(new Error(''))
      }
    },
    async [ActionsLogOut]({ commit }) {
      commit(LOGOUT)
    },
    async [ActionsEditUserInfo]({ commit, state }, { key, value }) {
      const userInfo = { ...state[USERINFO].userInfo }
      userInfo[key] = value
      try {
        await editUserInfo(userInfo)
        commit(SETUserInfoValues, { key, value })
        return true
      } catch (error) {
        return Promise.reject(error)
      }
    }
  },
  namespaced: true
}

export default user
